package com.sun;

/**
 * https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/
 */
public class Test28找出字符串中第一个匹配项的下标 {
    public static void main(String[] args){
        String haystack = "mississippi";
        String needle = "issip";
        int position = strStr3(haystack, needle);
        System.out.println(position);
    }

    /**
     * 方法一：自己
     */
    public static int strStr1(String haystack, String needle) {
        int needleLength = needle.length();
        for (int i = 0; i <= haystack.length() - needleLength; i++) {
            if (needle.equals(haystack.substring(i,i+needleLength))){
                return i;
            }
        }
        return -1;
    }
    /**
     * 方法2：不调用api1
     */
    public static int strStr2(String haystack, String needle) {
        char[] haystackChars = haystack.toCharArray();
        char[] needleChars = needle.toCharArray();
        int haystackLength = haystack.length();
        int needleLength = needle.length();
        for (int i = 0; i < haystackLength - needleLength; i++) {
            int m = 0, q = i;
            while (m < needleLength && needleChars[m] == haystackChars[q]){
                m++;
                q++;
            }
            if (m == needleLength){
                return i;
            }
        }
        return -1;
    }
    /**
     * 方法3：不调用api2
     */
    public static int strStr3(String haystack, String needle) {
        char[] haystackChars = haystack.toCharArray();
        char[] needleChars = needle.toCharArray();
        int i = 0, j = 0;
        while (i < needleChars.length && j < haystackChars.length){
            if (needleChars[i] == haystackChars[j]){
                i++;
                j++;
            }else {
                j = j - i + 1;
                i = 0;
            }
            if (i == needleChars.length){
                return j - i;
            }
        }
        return -1;
    }

}
